import { useEffect, useMemo, useState } from "react";
import "../assets/css/course.scss";
import Head from "../components/head";
import Top from "../components/Top/top";
import api from "../util/api";
import { Toast, SwipeCell, Button, ProductCard } from "react-vant";

export default function Course() {
  const [courseList, setCourList] = useState([]); //存储课程数据
  
  // 获取当前登录这信息
  const publisher = useMemo(() => {
    return JSON.parse(localStorage.getItem("user")).note._id;
  }, []); 

  //请求数据
  const getCourseList = async () => {
    const data = await api.get("/users/courselist", {
      params: { publisher: publisher },
    });
    if (data.code === 200) {
      setCourList(data.data);
    } else {
      Toast.fail("数据请求失败");
    }
  };
   // 进行网络请求
  useEffect(() => {
    getCourseList();
  }, []);

  // 删除课程
  const handelDel =(id,arr)=>{
      api.delete('/users/delcourse',{params : {id,arr : arr}})
      getCourseList()
  }

  return (
    <div className="course-home">
      <Head />
      <Top />
      <div className="course-main">
        {courseList.map((item) => (
          <div className="course-main-item" key={item._id}>
            <SwipeCell
              rightAction={
                <>
                  <Button square type="danger">
                    编辑
                  </Button>
                  <Button square type="primary" onClick={()=>handelDel(item._id,item.chapters)}>
                    删除
                  </Button>
                </>
              }
            >
              <ProductCard
                price={item.price}
                desc={item.courseDesc}
                title={item.title}
                thumb={item.img}
              />
            </SwipeCell>
          </div>
        ))}
      </div>
    </div>
  );
}
